package com.xzc.lease.web.admin.service.impl;

import com.xzc.lease.common.constant.RedisConstant;
import com.xzc.lease.model.entity.*;
import com.xzc.lease.web.admin.mapper.*;
import com.xzc.lease.web.admin.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzc.lease.model.entity.*;
import com.xzc.lease.model.enums.ItemType;
import com.xzc.lease.web.admin.mapper.*;
import com.xzc.lease.web.admin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.lease.web.admin.vo.attr.AttrValueVo;
import com.xzc.lease.web.admin.vo.graph.GraphVo;
import com.xzc.lease.web.admin.vo.room.RoomDetailVo;
import com.xzc.lease.web.admin.vo.room.RoomItemVo;
import com.xzc.lease.web.admin.vo.room.RoomQueryVo;
import com.xzc.lease.web.admin.vo.room.RoomSubmitVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 徐生
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {

    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 保存或更新房间信息
     *
     * @param roomSubmitVo
     */
    public void saveOrUpdateRoom(RoomSubmitVo roomSubmitVo) {
        //判断当前的操作是保存还是更新，true为更新，反之为保存
        boolean isUpdate = roomSubmitVo.getId() != null;

        //保存roomInfo的基础属性
        super.saveOrUpdate(roomSubmitVo);

        //更新的操作：先把原属性删除，再插入新数据
        if (isUpdate) {
            //删除房间关联的 图片、属性、配套、标签、支付方式、可选租期列表信息
            deleteBatch(roomSubmitVo.getId());
            //为更新操作时才删除缓存
            String key = RedisConstant.APP_ROOM_PREFIX + roomSubmitVo.getId();
            redisTemplate.delete(key);
        }

        //1、插入图片列表
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>();
            graphVoList.forEach(graphVo -> {
                        GraphInfo graphInfo = new GraphInfo();
                        graphInfo.setUrl(graphVo.getUrl());
                        graphInfo.setName(graphVo.getName());
                        graphInfo.setItemType(ItemType.ROOM);
                        graphInfo.setItemId(roomSubmitVo.getId());
                        graphInfoList.add(graphInfo);
                    }
            );
            graphInfoService.saveBatch(graphInfoList);
        }

        //2、插入属性信息列表
        List<Long> attrValueIdList = roomSubmitVo.getAttrValueIds();
        if (!CollectionUtils.isEmpty(attrValueIdList)) {
            ArrayList<RoomAttrValue> attrValueList = new ArrayList<>();
            attrValueIdList.forEach(attrValueId -> {
                RoomAttrValue roomAttrValue = RoomAttrValue.builder()
                        .roomId(roomSubmitVo.getId())
                        .attrValueId(attrValueId)
                        .build();
                attrValueList.add(roomAttrValue);
            });
            roomAttrValueService.saveBatch(attrValueList);
        }

        //3、插入配套信息列表
        List<Long> facilityInfoIdList = roomSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIdList)) {
            ArrayList<RoomFacility> facilityList = new ArrayList<>();
            facilityInfoIdList.forEach(facilityInfoId -> {
                RoomFacility roomFacility = RoomFacility.builder()
                        .roomId(roomSubmitVo.getId())
                        .facilityId(facilityInfoId)
                        .build();
                facilityList.add(roomFacility);
            });
            roomFacilityService.saveBatch(facilityList);
        }

        //4、插入标签信息列表
        List<Long> labelInfoIdList = roomSubmitVo.getLabelInfoIds();
        if (!CollectionUtils.isEmpty(labelInfoIdList)) {
            ArrayList<RoomLabel> roomLabelList = new ArrayList<>();
            labelInfoIdList.forEach(labelInfoId -> {
                RoomLabel roomLabel = RoomLabel.builder()
                        .roomId(roomSubmitVo.getId())
                        .labelId(labelInfoId)
                        .build();
                roomLabelList.add(roomLabel);
            });
            roomLabelService.saveBatch(roomLabelList);
        }

        //5、插入支付方式列表
        List<Long> paymentTypeIdList = roomSubmitVo.getPaymentTypeIds();
        if (!CollectionUtils.isEmpty(paymentTypeIdList)) {
            ArrayList<RoomPaymentType> roomPaymentTypeList = new ArrayList<>();
            paymentTypeIdList.forEach(paymentTypeId -> {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder()
                        .roomId(roomSubmitVo.getId())
                        .paymentTypeId(paymentTypeId)
                        .build();
                roomPaymentTypeList.add(roomPaymentType);
            });
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }

        //6、插入可选租期列表
        List<Long> leaseTermIdList = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIdList)) {
            ArrayList<RoomLeaseTerm> roomLeaseTermList = new ArrayList<>();
            paymentTypeIdList.forEach(leaseTermId -> {
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder()
                        .roomId(roomSubmitVo.getId())
                        .leaseTermId(leaseTermId)
                        .build();
                roomLeaseTermList.add(roomLeaseTerm);
            });
            roomLeaseTermService.saveBatch(roomLeaseTermList);
        }
    }


    @Autowired
    private RoomInfoMapper roomInfoMapper;

    /**
     * 根据条件分页查询房间列表
     *
     * @param page
     * @param queryVo
     * @return
     */
    public IPage<RoomItemVo> pageItem(Page<RoomItemVo> page, RoomQueryVo queryVo) {
        return roomInfoMapper.pageItem(page, queryVo);
    }


    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private RoomAttrValueMapper roomAttrValueMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private PaymentTypeMapper paymentTypeMapper;
    @Autowired
    private LeaseTermMapper leaseTermMapper;

    /**
     * 根据roomId获取房间详细信息
     *
     * @param id
     * @return
     */
    public RoomDetailVo getDetailByRoomId(Long id) {
        //1、先根据房间id查询房间信息
        RoomInfo roomInfo = super.getById(id);
//        RoomInfo roomInfo = roomInfoMapper.selectById(id);

        //2、查询所属公寓信息
//        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(id);
        ApartmentInfo apartmentInfo = apartmentInfoMapper.getByRoomId(id);
        //3、查询房间 图片列表
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.ROOM, roomInfo.getId());
        //4、查询房间 属性信息列表
        List<AttrValueVo> attrValueVoList = roomAttrValueMapper.getListByRoomId(id);
        //5、查询房间 配套信息列表
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.getListByRoomId(id);
        //6、查询房间 标签信息列表
        List<LabelInfo> labelInfoList = labelInfoMapper.getListByRoomId(id);
        //7、查询房间 支付方式列表
        List<PaymentType> paymentTypeList = paymentTypeMapper.getListByRoomId(id);
        //8、查询房间 可选租期列表
        List<LeaseTerm> leaseTermList = leaseTermMapper.getListByRoomId(id);

        //9、组装结果返回
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        //前面的参数值赋值给后面的参数值
        BeanUtils.copyProperties(roomInfo, roomDetailVo);
        roomDetailVo.setApartmentInfo(apartmentInfo);
        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setAttrValueVoList(attrValueVoList);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        roomDetailVo.setLabelInfoList(labelInfoList);
        roomDetailVo.setPaymentTypeList(paymentTypeList);
        roomDetailVo.setLeaseTermList(leaseTermList);
        return roomDetailVo;
    }


    /**
     * 根据roomId删除房间信息
     *
     * @param id
     */
    public void removeByRoomId(Long id) {
        //1、先删除房间信息
        super.removeById(id);
        //2、再删除房间关联的 图片、属性、配套、标签、支付方式、可选租期列表信息
        deleteBatch(id);

        //在删除房间时，删除缓存
        String key = RedisConstant.APP_ROOM_PREFIX + id;
        redisTemplate.delete(key);
    }


    public void deleteBatch(Long roomId) {
        //1、更新图片列表
        LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
        graphQueryWrapper.eq(GraphInfo::getId, roomId);
        graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
        graphInfoService.remove(graphQueryWrapper);

        //2、更新属性信息列表
        LambdaQueryWrapper<RoomAttrValue> attrQueryWrapper = new LambdaQueryWrapper<>();
        attrQueryWrapper.eq(RoomAttrValue::getRoomId, roomId);
        roomAttrValueService.remove(attrQueryWrapper);

        //3、更新配套信息列表
        LambdaQueryWrapper<RoomFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(RoomFacility::getRoomId, roomId);
        roomFacilityService.remove(facilityQueryWrapper);

        //4、更新标签信息列表
        LambdaQueryWrapper<RoomLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(RoomLabel::getRoomId, roomId);
        roomLabelService.remove(labelQueryWrapper);

        //5、更新支付方式列表
        LambdaQueryWrapper<RoomPaymentType> paymentTypeQueryWrapper = new LambdaQueryWrapper<>();
        paymentTypeQueryWrapper.eq(RoomPaymentType::getRoomId, roomId);
        roomPaymentTypeService.remove(paymentTypeQueryWrapper);

        //6、更新可选租期列表
        LambdaQueryWrapper<RoomLeaseTerm> leaseTermQueryWrapper = new LambdaQueryWrapper<>();
        leaseTermQueryWrapper.eq(RoomLeaseTerm::getRoomId, roomId);
        roomLeaseTermService.remove(leaseTermQueryWrapper);
    }
}




